package com.auto.survey.activity.test

import com.auto.survey.activity.bluetooth.BluetoothManagerUtil
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException

class TestCommandExecutor(activity: TestActivity, bluetoothmanager: BluetoothManagerUtil, comm: String) :
    ICommanExecutor {

    val bluetoothManager = bluetoothmanager
    val testActivity = activity
    val command = comm

    override suspend fun execute(): String {
        return suspendCancellableCoroutine { continuation ->
            // 检查蓝牙连接
            val devices = bluetoothManager.getConnectedDevices2()
            if (devices.isNullOrEmpty()) {
                continuation.resumeWithException(IllegalStateException("没有连接的蓝牙设备"))
                return@suspendCancellableCoroutine
            }

            val device = devices[0]

            // 设置一次性回调
            testActivity.setResultCallback { result ->
                // 确保只回调一次
                if (!continuation.isCancelled) {
                    continuation.resume(result)
                }
            }

            // 发送数据
            try {
                bluetoothManager.sendDataByClient(device, command.toByteArray())
            } catch (e: Exception) {
                if (!continuation.isCancelled) {
                    continuation.resumeWithException(e)
                }
            }

        }
    }


}